package com.example.demo;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpRetryException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int GET_RESULT = 1001;
    private static final int GET_IMG = 1003;
    private static final int POST_RESULT = 1002;
    private static final int HUC_GET_RESULT = 1004;
    private static final int HUC_POST_RESULT =1005 ;
    private EditText editText;
    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if(msg.what == GET_RESULT){
                    String html = (String) msg.obj;
                    Intent intent = new Intent(MainActivity.this,HTTPGETActivity.class);
                    intent.putExtra("CONTENT",html);
                    startActivity(intent);
                }
                if(msg.what==POST_RESULT){
                    String html = (String) msg.obj;
                    Intent intent = new Intent(MainActivity.this,HTTPOSTActivity.class);
                    intent.putExtra("CONTENT",html);
                    startActivity(intent);
                }
                if (msg.what==GET_IMG){
                    Bitmap bitmap = (Bitmap) msg.obj;
                    Intent intent = new Intent(MainActivity.this,HttpUrlConnectionGetImgActivity.class);
                    intent.putExtra("IMG", bitmap);
                    startActivity(intent);
                }
                if (msg.what==HUC_GET_RESULT){
                    String html =  msg.obj.toString();
                    Intent intent = new Intent(MainActivity.this,HttpUrlConnectionGetActivity.class);
                    intent.putExtra("CONTENT", html);
                    startActivity(intent);
                }

                return false;
            }
        });

        editText = findViewById(R.id.edt_phone);
        findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String phone = editText.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        useHttpGet(phone);
                    }
                }).start();
            }
        });

        findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String phone = editText.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        useHttpPost(phone);
                    }
                }).start();
            }
        });
        findViewById(R.id.btn3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String phone = editText.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        useHttpUrlConnectionGet(phone);
                    }
                }).start();
            }
        });
        findViewById(R.id.btn4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String phone = editText.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        useHttpUrlConnectionPost(phone);
                    }
                }).start();
            }
        });
        findViewById(R.id.btn5).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        useHttpUrlConnectionGetImg();
                    }
                }).start();
            }
        });

    }



    private void useHttpUrlConnectionPost(String phone) {
        String phoneBaseUrl = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
        try {
            URL url = new URL(phoneBaseUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            String body ="mobileCode="+phone+"&userID=";
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            bufferedWriter.write(body);
            bufferedWriter.flush();
            bufferedWriter.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));

            StringBuffer stringBuffer = new StringBuffer();
            String line = bufferedReader.readLine();

            while (line!=null){
                stringBuffer.append(line);
                line = bufferedReader.readLine();
            }

            Message message = Message.obtain();
            message.what = HUC_POST_RESULT;
            message.obj = stringBuffer;
            handler.sendMessage(message);

            Log.e(TAG,"stringBuffer ="+stringBuffer.toString());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void useHttpUrlConnectionGet(String phone) {
        String strUrl = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=";
        strUrl = strUrl.concat(phone).concat("&userID=");

        try {
            URL url = new URL(strUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

             InputStream inputStream = httpURLConnection.getInputStream();
             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));

             StringBuffer stringBuffer = new StringBuffer();
             String line = bufferedReader.readLine();

            while (line!=null){
                stringBuffer.append(line);
                line = bufferedReader.readLine();
            }

            Message message = Message.obtain();
            message.what = HUC_GET_RESULT;
            message.obj = stringBuffer;
            handler.sendMessage(message);

            Log.e(TAG,"stringBuffer ="+stringBuffer.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void useHttpGet(String phone){
        String url = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=";
        url = url.concat(phone).concat("&userID=");
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int code = httpResponse.getStatusLine().getStatusCode();
            Log.e(TAG, "code = " + code);
//            String htmlContent = getHtmlContent(httpResponse);
//            Log.e(TAG, htmlContent);
            String htmlContent = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            Log.e(TAG, htmlContent);

            Message message = Message.obtain();
            message.what = POST_RESULT;
            message.obj = htmlContent;
            handler.sendMessage(message);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void useHttpUrlConnectionGetImg() {
        String strUrl = "http://jsxy.gdcp.cn/UploadFile/2/2012/5/6/201256132519932.jpg";

        try {
            URL url = new URL(strUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            int code = httpURLConnection.getResponseCode();
            Log.e(TAG,"code = "+code);

            Bitmap bitmap = BitmapFactory.decodeStream(httpURLConnection.getInputStream());
            Message message = Message.obtain();
            message.what = GET_IMG;
            message.obj = bitmap;
            handler.sendMessage(message);




            /*InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));

            StringBuffer stringBuffer = new StringBuffer();
            String line = bufferedReader.readLine();

            while (line!=null){
                stringBuffer.append(line);
                line = bufferedReader.readLine();
            }
            Log.e(TAG,"stringBuffer ="+stringBuffer.toString());*/

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void useHttpPost(String phone) {
        String url = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
        HttpPost httpPost = new HttpPost(url);
        HttpClient httpClient = new DefaultHttpClient();
        List<NameValuePair> nameValuePairList = new ArrayList<>();
        nameValuePairList.add(new BasicNameValuePair("mobileCode", phone));
        nameValuePairList.add(new BasicNameValuePair("userID", ""));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            String htmlContent = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            Log.e(TAG, htmlContent);

            Message message = Message.obtain();
            message.what = GET_RESULT;
            message.obj = htmlContent;
            handler.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=string&userID=string


    private String getHtmlContent(HttpResponse httpResponse) throws IOException {
        InputStream inputStream = httpResponse.getEntity().getContent();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer stringBuffer = new StringBuffer();
        String line = bufferedReader.readLine();
        while(line != null){
            stringBuffer.append(line);
            line = bufferedReader.readLine();
        }
        inputStream.close();
        bufferedReader.close();
        return  stringBuffer.toString();
    }
}
